package com.zucc.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.zucc.controller.req.DeviceAddReq;
import com.zucc.controller.req.DeviceExcelImportReq;
import com.zucc.controller.req.DeviceModifyReq;
import com.zucc.controller.req.DeviceSearchReq;
import com.zucc.controller.resp.DeviceResp;
import com.zucc.entity.Device;
import com.zucc.entity.DeviceMapper;
import com.zucc.entity.base.MyMapper;
import com.zucc.exception.SyzxException;
import com.zucc.service.DeviceService;
import com.zucc.service.base.MyServiceImpl;
import com.zucc.service.base.PageData;
import com.zucc.util.MyPageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author : charspan
 * @Description :
 * @create : 2021-12-23 5:49 下午
 */
@Service
public class DeviceServiceImpl extends MyServiceImpl<Device> implements DeviceService {
    @Resource
    private DeviceMapper deviceMapper;

    @Override
    public MyMapper<Device> mapper() {
        return deviceMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDeviceExcel(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(0);
        try {
            List<DeviceExcelImportReq> list = ExcelImportUtil.importExcel(file.getInputStream(), DeviceExcelImportReq.class, params);
            System.out.println(list);
            List<Device> devices = new ArrayList<>();
            for (DeviceExcelImportReq deviceExcelImportReq : list) {
                Device device = new Device();
                BeanUtil.copyProperties(deviceExcelImportReq, device);
                device.setDelFlag(0);
                device.setCreateTime(DateUtil.date());
                device.setModifyTime(DateUtil.date());
                device.setStatus(0);
                // todo 验证
                device.setApprovalStatus(0);
                devices.add(device);
            }
            deviceMapper.insertList(devices);
        } catch (Exception e) {
            throw new SyzxException("设备导入表格格式有误，请检查（价格、数量等是否符合数学规范）");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DeviceAddReq req) {
        Device device = new Device();
        BeanUtil.copyProperties(req, device);
        device.setDelFlag(0);
        device.setCreateTime(DateUtil.date());
        device.setModifyTime(DateUtil.date());
        device.setStatus(0);
        device.setApprovalStatus(0);
        super.saveKey(device);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(DeviceModifyReq req) {
        Device deviceExist = super.findById(req.getId());
        if (Objects.isNull(deviceExist)) {
            throw new SyzxException("系统找不到相应编号的分类信息");
        }
        BeanUtil.copyProperties(req, deviceExist, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        deviceExist.setModifyTime(DateUtil.date());
        super.updateSelective(deviceExist);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOne(Long id) {
        Device deviceExist = super.findById(id);
        if (Objects.isNull(deviceExist)) {
            throw new SyzxException("系统找不到相应编号的分类信息");
        }
        deviceExist.setDelFlag(1);
        deviceExist.setDeleteTime(DateUtil.date());
        super.updateSelective(deviceExist);
    }

    @Override
    public PageData<DeviceResp> page(DeviceSearchReq req) {
        Example example = new Example(Device.class);
        example.setOrderByClause("modify_time DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delFlag", 0);

        if (StrUtil.isNotBlank(req.getCategoryNumber())) {
            criteria.andLike("categoryNumber", "%" + req.getCategoryNumber() + "%");
        }
        if (StrUtil.isNotBlank(req.getDeviceNumber())) {
            criteria.andLike("deviceNumber", "%" + req.getDeviceNumber() + "%");
        }
        if (StrUtil.isNotBlank(req.getDeviceName())) {
            criteria.andLike("deviceName", "%" + req.getDeviceName() + "%");
        }
        if (StrUtil.isNotBlank(req.getModel())) {
            criteria.andLike("model", "%" + req.getModel() + "%");
        }
        if (StrUtil.isNotBlank(req.getSpecifications())) {
            criteria.andLike("specifications", "%" + req.getSpecifications() + "%");
        }
        if (StrUtil.isNotBlank(req.getBuyDate())) {
            criteria.andLike("buyDate", "%" + req.getBuyDate() + "%");
        }
        if (StrUtil.isNotBlank(req.getScrapDate())) {
            criteria.andLike("scrapDate", "%" + req.getScrapDate() + "%");
        }
        if (StrUtil.isNotBlank(req.getUseUnit())) {
            criteria.andLike("useUnit", "%" + req.getUseUnit() + "%");
        }
        if (Objects.nonNull(req.getUserId())) {
            criteria.andEqualTo("userId", req.getUserId());
        }
        if (StrUtil.isNotBlank(req.getOldAddress())) {
            criteria.andLike("oldAddress", "%" + req.getOldAddress() + "%");
        }
        if (StrUtil.isNotBlank(req.getNewAddress())) {
            criteria.andLike("newAddress", "%" + req.getNewAddress() + "%");
        }
        if (Objects.nonNull(req.getSource())) {
            criteria.andEqualTo("source", req.getSource());
        }
        if (Objects.nonNull(req.getStatus())) {
            criteria.andEqualTo("status", req.getStatus());
        }
        if (StrUtil.isNotBlank(req.getRemarks())) {
            criteria.andLike("remarks", "%" + req.getRemarks() + "%");
        }
        if (Objects.nonNull(req.getApprovalStatus())) {
            criteria.andEqualTo("approvalStatus", req.getApprovalStatus());
        }

        PageData<Device> pageData = super.findByPage(req, example);
        PageData<DeviceResp> convert = MyPageUtil.convert(pageData, DeviceResp.class);
        return convert;
    }
}
